package com.company.common.function.jwttoken;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

public class Test {

    private long time = 1000 * 60 * 60 * 24;
    private String signature = "admin";

    public void jwt() {
        JwtBuilder jwtbuilder = Jwts.builder();
        String jwtToken = jwtbuilder
                //header
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //payload
                .claim("username", "tom")
                .claim("role", "admin")
                .setSubject("admin-test")
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256, signature)
                .compact();
        System.out.println(jwtToken);

    }

    public void parse() {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFkbWluLXRlc3QiLCJleHAiOjE2NDU1MzM1NTQsImp0aSI6IjcxMTk5OWRmLWVjOTEtNDVmZi05NDA3LTA4MTkxZmI0MzU1MCJ9.rgn2lTsLc0_IO8me3MUyNvLTx42FeVbnZb6y0RqdreEeyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFkbWluLXRlc3QiLCJleHAiOjE2NDU1MzM1NTQsImp0aSI6IjcxMTk5OWRmLWVjOTEtNDVmZi05NDA3LTA4MTkxZmI0MzU1MCJ9.rgn2lTsLc0_IO8me3MUyNvLTx42FeVbnZb6y0RqdreE";
        JwtParser jwtparser = Jwts.parser();
        Jws<Claims> claimsJws = jwtparser.setSigningKey(signature).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        System.out.println(body.get("username"));
        System.out.println(body.get("role"));
        System.out.println(body.getId());
        System.out.println(body.getSubject());
        System.out.println(body.getExpiration());

    }
}
